package com.example.security.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @className: UserServiceImpl
 * @author: YTF
 * @date: 2025/4/30 11:55
 * @description:
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Users>  {

    @Autowired
    private AuthoritiesMapper authoritiesMapper;
    public Users getUserByUsername(String username) {
        Users users = this.lambdaQuery().eq(Users::getUsername, username).one();
        LambdaQueryWrapper<Authorities> lambdaQueryWrapper = new LambdaQueryWrapper<Authorities>()
                .select(Authorities::getAuthority)
                .eq(Authorities::getUsername, username);
        return serUserAuthorities(users, lambdaQueryWrapper);
    }
    public Users getUserByPhone(String phone) {
        Users users = this.lambdaQuery().eq(Users::getPhone, phone).one();
        LambdaQueryWrapper<Authorities> lambdaQueryWrapper = new LambdaQueryWrapper<Authorities>()
                .select(Authorities::getAuthority)
                .eq(Authorities::getUsername, users.getUsername());
        return serUserAuthorities(users, lambdaQueryWrapper);

    }

    private Users serUserAuthorities(Users users, LambdaQueryWrapper<Authorities> lambdaQueryWrapper) {
        List<String> authorities = authoritiesMapper.selectList(lambdaQueryWrapper).stream()
                .map(Authorities::getAuthority)
                .filter(Objects::nonNull)
                .map(authority ->
                        authority.startsWith("ROLE_") ?
                                authority.substring(5) :  // 移除开头的 ROLE_
                                authority
                )
                .collect(Collectors.toList());
        users.setAuthorities(authorities);
        return users;
    }
}
